/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.utils;

import cn.easyplatform.EasyPlatformRuntimeException;
import cn.easyplatform.jms.PooledConnectionFactory;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Mirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public final class JmsUtils {

    private final static Logger log = LoggerFactory.getLogger(JmsUtils.class);

    /**
     * 创建JMS连接池
     *
     * @param set
     * @return
     */
    public final static ConnectionFactory createConnectionFactory(Set<Map.Entry<String, String>> set) {
        Iterator<Map.Entry<String, String>> itr = set.iterator();
        String connectionFactory = null;
        while (itr.hasNext()) {
            Map.Entry<String, String> entry = itr.next();
            if (entry.getKey().equals("connectionFactory")) {
                connectionFactory = entry.getValue();
                break;
            }
        }
        if (connectionFactory == null)
            throw new EasyPlatformRuntimeException("Jms connectionFactory not found");
        if (log.isDebugEnabled())
            log.debug("create a jms connection factory:{}", connectionFactory);
        try {
            Class clazz = Class.forName(connectionFactory);
            PooledConnectionFactory pcfactory = new PooledConnectionFactory();
            Mirror cf = Mirror.me(clazz);
            boolean pooled = false;
            for (Map.Entry<String, String> entry : set) {
                if (entry.getKey().startsWith("pool")) {
                    pooled = true;
                    break;
                }
            }
            Mirror pcf = null;
            if (pooled)
                pcf = Mirror.me(PooledConnectionFactory.class);
            Object factory = clazz.newInstance();
            for (Map.Entry<String, String> entry : set) {
                if (!entry.getKey().startsWith("pool")) {
                    if (entry.getKey().equals("trustedPackages"))
                        cf.getInjecting(entry.getKey()).inject(factory, Arrays.asList(entry.getValue().split(";")));
                    else if (!entry.getKey().equals("connectionFactory"))
                        cf.getInjecting(entry.getKey()).inject(factory, entry.getValue());
                } else if (pooled)
                    pcf.getInjecting(entry.getKey().substring(5)).inject(pcfactory, entry.getValue());
            }
            if (pooled) {
                pcfactory.setConnectionFactory(factory);
                return pcfactory;
            } else
                return (ConnectionFactory) factory;
        } catch (Exception e) {
            throw Lang.wrapThrow(e);
        }
    }

    public final static void close(Connection connection, Session session, MessageProducer... producers) {
        if (producers.length > 0) {
            for (MessageProducer producer : producers) {
                try {
                    producer.close();
                } catch (Exception e) {
                }
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.stop();
            } catch (Exception e) {
            }
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }

    public final static void close(Connection connection, Session session, MessageConsumer... consumers) {
        if (consumers.length > 0) {
            for (MessageConsumer consumer : consumers) {
                try {
                    consumer.close();
                } catch (Exception e) {
                }
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.stop();
            } catch (Exception e) {
            }
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}
